package com.ruoyi.classai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.classai.domain.EwcChapterPptmaterial;
import com.ruoyi.classai.domain.EwcChapterResource;
import com.ruoyi.classai.domain.EwcTeachingResource;
import com.ruoyi.classai.domain.dto.chapterresource.EwcChapterResourceAddDto;
import com.ruoyi.classai.domain.dto.chapterresource.EwcChapterResourceQueryDto;
import com.ruoyi.classai.domain.dto.resource.EwcTeachingResourceSaveDto;
import com.ruoyi.classai.domain.dto.resource.EwcTeachingResourceSingleSaveDto;
import com.ruoyi.classai.domain.vo.resource.EwcTeachingResourceAnalyseDetailVo;
import com.ruoyi.classai.mapper.EwcChapterResourceMapper;
import com.ruoyi.classai.service.IEwcChapterResourceService;
import com.ruoyi.classai.utils.FileUtil;
import com.ruoyi.common.core.context.ThirdSessionHolder;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * 老师资源库Service业务层处理
 *
 * @author lcj
 * @date 2025-03-26
 */
@Service
public class EwcChapterResourceServiceImpl extends ServiceImpl<EwcChapterResourceMapper, EwcChapterResource> implements IEwcChapterResourceService {

    /**
     * 查询老师资源库列表
     *
     * @param dto 老师资源库信息
     * @return 老师资源库集合
     */
    @Override
    public List<EwcChapterResource> selectChapterResourceList(EwcChapterResourceQueryDto dto) {
        LambdaQueryWrapper<EwcChapterResource> queryWrapper = new LambdaQueryWrapper<>();

        // 添加关键字查询条件
        if (StringUtils.isNotBlank(dto.getKey())) {
            // 查询资源名称
            queryWrapper.like(EwcChapterResource::getResourceName, dto.getKey())
                    .or()
                    // 使用exists子查询关联课程表，根据课程名称查询
                    .exists("SELECT 1 FROM ewc_course c WHERE c.id = ewc_chapter_resource.course_id AND c.course_name LIKE CONCAT('%', '" + dto.getKey() + "', '%')")
                    .or()
                    // 使用exists子查询关联章节表，根据章节名称查询
                    .exists("SELECT 1 FROM ewc_chapter ch WHERE ch.id = ewc_chapter_resource.chapter_id AND ch.chapter_name LIKE CONCAT('%', '" + dto.getKey() + "', '%')");
        }
        if (Objects.nonNull(dto.getSubjectType())) {
            queryWrapper.eq(EwcChapterResource::getSubjectType, dto.getSubjectType());
        }
        if (Objects.nonNull(dto.getFileType())) {
            queryWrapper.eq(EwcChapterResource::getFileType, dto.getFileType());
        }
        queryWrapper.eq(EwcChapterResource::getCreatorId, ThirdSessionHolder.getThirdSession().getId())
                .eq(EwcChapterResource::getStatus,1);
        queryWrapper.orderByDesc(EwcChapterResource::getCreateTime);
        List<EwcChapterResource> list = this.list(queryWrapper);

        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertChapterResource(EwcChapterResourceAddDto dto) {
        // 当前时间
        Date nowDate = DateUtils.getNowDate();

        EwcChapterResource resource = new EwcChapterResource();
        BeanUtils.copyProperties(dto, resource, "id");
        // 设置创建者和创建时间
        resource.setCreator(ThirdSessionHolder.getThirdSession().getAccount());
        resource.setCreatorId(ThirdSessionHolder.getThirdSession().getId());
        resource.setCreateTime(nowDate);
        resource.setStatus(1);
        resource.setResourceName(DateUtils.dateTimeNow());
        // 处理文件后缀和类型
        if (StringUtils.isNotBlank(dto.getResourceUrl())) {
            String resourceSuffix = FileUtil.getResourceSuffix(dto.getResourceUrl());
            resource.setFileDetails(resourceSuffix);
            resource.setFileType(FileUtil.getFileType(resourceSuffix));
        }
        this.save(resource);
    }

    @Override
    public EwcChapterResource getChapterResourceById(String id) {
        EwcChapterResource resource = this.getById(id);
        if (Objects.isNull(resource) || resource.getStatus() == 0) {
            throw new GlobalException("资源不存在");
        }
        return resource;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateChapterResource(EwcChapterResourceAddDto dto) {
        if (StringUtils.isEmpty(dto.getId())) {
            throw new GlobalException("ID不存在");
        }
        EwcChapterResource oldResource = this.getById(dto.getId());
        if (Objects.isNull(oldResource) || oldResource.getStatus() == 0) {
            throw new GlobalException("资源不存在");
        }
        String newResourceName = dto.getResourceName();
        String oldResourceName = oldResource.getResourceName();
        if (!newResourceName.equals(oldResourceName)) {
            LambdaQueryWrapper<EwcChapterResource> queryWrapper = new LambdaQueryWrapper<EwcChapterResource>()
                    .eq(EwcChapterResource::getResourceName, newResourceName)
                    .eq(StringUtils.isNotBlank(dto.getChapterId()), EwcChapterResource::getChapterId, dto.getChapterId())
                    .ne(EwcChapterResource::getId, dto.getId());
            if (this.count(queryWrapper) > 0) {
                throw new GlobalException("该章节下资源名称已存在");
            }
        }
        BeanUtils.copyProperties(dto, oldResource);
        Date nowDate = DateUtils.getNowDate();
        oldResource.setUpdateTime(nowDate);
        // 处理文件后缀和类型
        if (StringUtils.isNotBlank(dto.getResourceUrl())) {
            String resourceSuffix = FileUtil.getResourceSuffix(dto.getResourceUrl());
            oldResource.setFileDetails(resourceSuffix);
            oldResource.setFileType(FileUtil.getFileType(resourceSuffix));
        }
        this.updateById(oldResource);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteChapterResourceByIds(List<String> ids) {
        this.removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveTeachingResource(EwcTeachingResourceSaveDto ewcTeachingResourceSaveDto, EwcTeachingResourceAnalyseDetailVo teachingResourceAnalyseDetail) {
        //查询是否存在
        LambdaQueryWrapper<EwcChapterResource> queryWrapper = new LambdaQueryWrapper<EwcChapterResource>()
                .eq(EwcChapterResource::getTeachingResourceId, teachingResourceAnalyseDetail.getId())
                .eq(EwcChapterResource::getCreatorId, ThirdSessionHolder.getThirdSession().getId());
        long count = this.count(queryWrapper);
        if(count > 0){
            boolean delResult = this.remove(queryWrapper);
            if(!delResult){
                throw new GlobalException("数据异常");
            }
        }

        Date currentDate = new Date();
        //保存源资源数据
        EwcChapterResource Resource = new EwcChapterResource();
        Resource.setId(UUID.randomUUID().toString().replace("-", ""));
        Resource.setResourceName(teachingResourceAnalyseDetail.getResourceName()+"-源视频");
        Resource.setCreateTime(currentDate);
        Resource.setUpdateTime(currentDate);
        Resource.setCreatorId(ThirdSessionHolder.getThirdSession().getId());
        Resource.setCreator(ThirdSessionHolder.getThirdSession().getTeacherName());
        Resource.setStatus(1);
        String ResourceUrlRS = teachingResourceAnalyseDetail.getResourceUrl();
        Resource.setResourceUrl(ResourceUrlRS);
        if(ResourceUrlRS != null && !ResourceUrlRS.isEmpty()){
            int lastDotIndexRS = teachingResourceAnalyseDetail.getResourceUrl().lastIndexOf(".");
            if (lastDotIndexRS > 0) {
                String fileExtensionRS = teachingResourceAnalyseDetail.getResourceUrl().substring(lastDotIndexRS + 1);
                Resource.setFileDetails(fileExtensionRS);
            }
        }
        Resource.setFileType(ewcTeachingResourceSaveDto.getFileType());
        Resource.setSubjectType(teachingResourceAnalyseDetail.getSubjectType());
        Resource.setTeachingResourceId(teachingResourceAnalyseDetail.getId());
        boolean resourceSaveResult = this.save(Resource);
        if(!resourceSaveResult){
            throw new GlobalException("数据异常");
        }
        //保存AI解析资源数据
        EwcChapterResource AIAnalysesResource = new EwcChapterResource();
        AIAnalysesResource.setId(UUID.randomUUID().toString().replace("-", ""));
        AIAnalysesResource.setResourceName(teachingResourceAnalyseDetail.getResourceName()+"-解析视频");
        AIAnalysesResource.setCreateTime(currentDate);
        AIAnalysesResource.setUpdateTime(currentDate);
        AIAnalysesResource.setCreatorId(ThirdSessionHolder.getThirdSession().getId());
        AIAnalysesResource.setCreator(ThirdSessionHolder.getThirdSession().getTeacherName());
        AIAnalysesResource.setStatus(1);
        String ResourceUrlRSAI = teachingResourceAnalyseDetail.getAnalyResourceUrl();
        AIAnalysesResource.setResourceUrl(ResourceUrlRSAI);
        if(ResourceUrlRSAI != null && !ResourceUrlRSAI.isEmpty()){
            int lastDotIndexAIRS = teachingResourceAnalyseDetail.getAnalyResourceUrl().lastIndexOf(".");
            if (lastDotIndexAIRS > 0) {
                String fileExtensionAIRS = teachingResourceAnalyseDetail.getAnalyResourceUrl().substring(lastDotIndexAIRS + 1);
                AIAnalysesResource.setFileDetails(fileExtensionAIRS);
            }
        }
        AIAnalysesResource.setFileType(ewcTeachingResourceSaveDto.getFileType());
        AIAnalysesResource.setSubjectType(teachingResourceAnalyseDetail.getSubjectType());
        AIAnalysesResource.setTeachingResourceId(teachingResourceAnalyseDetail.getId());
        boolean AIResourceSaveResult = this.save(AIAnalysesResource);
        if(!AIResourceSaveResult){
            throw new GlobalException("数据异常");
        }
        return AjaxResult.success("提交成功！");
    }

    @Override
    public boolean updateTeachingResourceStatus(String id) {
        //查询是否存在
        LambdaQueryWrapper<EwcChapterResource> queryWrapper = new LambdaQueryWrapper<EwcChapterResource>()
                .eq(EwcChapterResource::getTeachingResourceId, id)
                .eq(EwcChapterResource::getCreatorId, ThirdSessionHolder.getThirdSession().getId());
        long count = this.count(queryWrapper);
        if(count > 0){
            EwcChapterResource entity = new EwcChapterResource();
            entity.setStatus(0);
            return this.update(entity,queryWrapper);
        }
        return true;
    }

    @Override
    public boolean SingleSaveTeachingResource(EwcTeachingResourceSingleSaveDto ETSingleSaveDto){
        Date currentDate = new Date();
        //保存源资源数据
        EwcChapterResource Resource = new EwcChapterResource();
        Resource.setId(UUID.randomUUID().toString().replace("-", ""));
        Resource.setResourceName(ETSingleSaveDto.getResourceName());
        Resource.setCreateTime(currentDate);
        Resource.setUpdateTime(currentDate);
        Resource.setCreatorId(ThirdSessionHolder.getThirdSession().getId());
        Resource.setCreator(ThirdSessionHolder.getThirdSession().getTeacherName());
        Resource.setStatus(1);
        String ResourceUrl = ETSingleSaveDto.getResourceUrl();
        Resource.setResourceUrl(ResourceUrl);
        if(ResourceUrl != null && !ResourceUrl.isEmpty()){
            int lastDotIndex = ResourceUrl.lastIndexOf(".");
            if (lastDotIndex > 0) {
                String fileExtension = ResourceUrl.substring(lastDotIndex + 1);
                Resource.setFileDetails(fileExtension);
            }
        }
        Resource.setFileType(ETSingleSaveDto.getFileType());
        Resource.setSubjectType(ETSingleSaveDto.getSubjectType());
        return this.save(Resource);
    }
}
